﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web.Mvc;
using Kkc.Model;

namespace Kkc.Application.Controllers
{
    [HandleError]
    public class PageLinkController: Controller
    {
        public ActionResult List(string route)
        {
            route = PrepareRoute(route);

            using (var entities = new KkcDataEntities())
            {
                var pageLinkQuery = from pl in entities.PageLinks
                                    where pl.SourceRoute.Equals(route, StringComparison.OrdinalIgnoreCase)
                                    select pl;

                var pageLinks = pageLinkQuery.ToList();
                foreach (var pageLink in pageLinks)
                {
                    pageLink.Url = ResolveUrl(pageLink.Url);
                }
                ViewData.Model = pageLinks;

                return View();
            }
        }

        private string PrepareRoute(string route)
        {
            if (route.StartsWith(HttpContext.Request.ApplicationPath))
                route = route.Substring(HttpContext.Request.ApplicationPath.Length + 1);

            if (string.IsNullOrEmpty(route))
                route = "Home/Index";

            route = route.TrimEnd('/');
            return route;
        }

        [Authorize(Roles = "Contributor")]
        [AcceptVerbs(HttpVerbs.Get)]
        public ActionResult Create(string route)
        {
            route = PrepareRoute(route);

            var pageLink = new PageLink
            {
                SourceRoute = route
            };

            ViewData.Model = pageLink;
            return View();
        }

        [Authorize(Roles = "Contributor")]
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Create(string route, string title, string url, string target)
        {
            using (var entities = new KkcDataEntities())
            {
                var pageLink = new PageLink
                {
                    Title = title,
                    SourceRoute = route,
                    Url = url,
                    Target = target
                };

                entities.AddToPageLinks(pageLink);
                entities.SaveChanges();

                return Redirect(url);
            }
        }

        private string ResolveUrl(string url)
        {
            if (string.IsNullOrEmpty(url))
                throw new ArgumentException("url");

            if (url.StartsWith("~/", StringComparison.Ordinal))
            {
                return Url.Content(url);
            }

            return url;
        }
    }
}
